<template>
    <div>
      <div class="map_big" :style="{'height':bigHeight}">
        <div class="map_title">
          <span><img src="../../assets/images/icon/locationGray.png" alt="" srcset=""></span>
          <span class="location_content">{{address}}</span>
          <span v-if="Enable" class="location_after" style="text-align: right;padding-right: 3%;">
            <a href="javascript:void(0)"  @click="openHandle('locationSure')" style="color:#39b5f9;padding-right:5px">确认</a>
            <a href="javascript:void(0)" @click="openHandle('locationCancel')">取消</a>
          </span>
          <span v-else-if="!typeShow" class="location_after" @click="openHandle('find_rim')">
            <img src="../../assets/images/icon/rim.png" alt="" srcset="">
            发现周边
          </span>
         
          <span v-else class="location_after" style="text-align: right;padding-right: 3%;" @click="openHandle('event_info')">
            事件详情
          </span>
        </div>
        <span class="allpx" v-if="typeShow" @click="openHandle('allpx')">
          <img src="../../assets/images/icon/allpx.png">
         
        </span>
        <span v-if="beginAction" v-show="typeShow" class="map_notification">
          <span class="handle_text" :style="{width:notificationWith}">
            <img src="../../assets/images/icon/laba.png" alt="" srcset="">
            <span><marquee scrollamount="3" :style="{width:marqueeWidth}">{{notification}}</marquee></span>
          </span>
          <span v-if="arriveFlag" class="handle_btn_div">
            <span  @click="openHandle('arrive')">到达现场</span>
          </span>
        </span>
        <span v-else  v-show="typeShow" class="map_notification">
          <span class="handle_text">
            <img src="../../assets/images/icon/laba.png" alt="" srcset="">
            <span><marquee :style="{width:marqueeWidth}">{{notification}}</marquee></span>
          </span>
          <span v-if="arriveFlag" class="handle_btn_div">
            <span  @click="openHandle('checkIn')">补充登记</span>
          </span>
        </span>
        <div class="container" :id="initName"></div> 
      </div>
    </div>
</template>
<script>
import { updateArriveState } from '@/assets/js/service'
export default {
  data() {
    return {
      openSimple:false,
      tabs:[{"code":"0","name":"请选择","parentId":"0","active":false}],
      defaultObj:{"code":"0","name":"请选择","parentId":"0","active":true},
      listArr:[],
      dataTree:[],
      tempList:[],
      initType:0,//0为全量初始化 1为层级初始化
      allIndexList:[],//总体缓存数据list 根据下标存储
      maps:{},//当前地图对象
      address:"",//当前点位地址
      marker:"",
      typeShow:"",
      notification:"",//离事发地约 3km，预计15分钟后到达现场  已出发4小时
      arriveFlag:true,
      beginAction:false,
      notificationWith:"75vw",
      marqueeWidth:"66vw",
      eventObj:{},
      locationSetStr:"",
    };
  },
  props: ["queryObj","bigHeight","initName","Enable"],
  watch:{
    arriveFlag(){
      console.log("arriveFlag 状态改变"+this.arriveFlag)
      if(this.arriveFlag){
        this.notificationWith="75vw";
        this.marqueeWidth="66vw"
      }else{
        this.notificationWith="100vw";
        this.marqueeWidth="86vw"
      }
    }
  },
  methods: {
    initData(treeData,initType){
      let _this=this;
      //console.log(treeData)
      _this.dataTree=treeData;
      _this.allIndexList=[];
      _this.initType=initType;
      if(treeData){
        _this.setListArr(_this.dataTree)
      }
    },
    setEventObj(_obj){
      this.eventObj=_obj;
    },
    secondToDate(result) {
      console.log(result+"秒");
        // var h = Math.floor(result / 3600) < 10 ? '0'+Math.floor(result / 3600) : Math.floor(result / 3600);
        // var m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
        // var s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60));
      var min=Math.floor(result%3600);
      console.log(Math.floor(result/3600) + "时" + Math.floor(min/60) + "分"+ result%60 + "秒");
          //return time;
      return result = Math.floor(result/3600) + ":" + Math.floor(min/60) + ":" + result%60;
    },
    changeNotification(_type){
      console.log("_type===>"+_type)
      if(_type=='1'){
        this.beginAction=true;
      }else{
        this.beginAction=false;
        this.notification="您还没有登记，请先登记";
      }
    },
    upNotification(time,distance,filltime){
      let distanceStr=""
      if(distance < 1000){
        distanceStr=distance+"米";
      }else{
        distanceStr=Math.round(((distance/100)/10)).toFixed(1) + "公里"
      }
      let timeTemp=this.secondToDate(time);
      console.log(timeTemp)
      let timeStr="";
      let timeArr= timeTemp.split(":");
      if(timeArr.length>0){
        timeStr="预计"+timeArr[0]+"小时"+timeArr[1]+"分钟后到达现场"
      }else{
        timeStr="预计"+timeArr[1]+"分钟后到达现场"
      }
      let beforeTimeStr="";
      let differenceStr= this.$GetDateDifference(filltime);
      if(differenceStr){
        let fristDiff=differenceStr.split(" ");
        if(fristDiff>1){
          beforeTimeStr=fristDiff[0]+fristDiff[1];
        }else{
          beforeTimeStr=fristDiff[0];
        }
        
      }
      let notificationStr="离事发地约 "+distanceStr+","+timeStr+" ,已出发"+beforeTimeStr;
      this.notification=notificationStr;
      //console.log(distanceStr,timeStr)
    },
    openHandle(_type){
      let _this=this;
      let param={"opentype":_type,"locationStr":_this.locationSetStr}
      if(_type=="arrive"){
        _this.updateArriveState();
      }else{
        console.log(_type)
         _this.$emit("handle",param)
         //_this.$showBottomToast(_type);
      }
    },
    updateArriveState(_state){
      let _this=this;
      if(_state&&_state=='1'){
         _this.arriveFlag=false;
      }else{
        let param={"eventid":_this.$store.state.eventId,"orgcode":_this.$store.state.user.orgcode};
        console.log(param)
        updateArriveState(param,function(res) {
          console.log("updateArriveState==>",res);
          if(res.status=='200'){
            _this.arriveFlag=false;
            _this.$showBottomToast("到达现场状态更新成功","success");
            console.log("updateArriveState 更新成功")
          }else{
            _this.$showBottomToast("到达现场状态更新失败","cancel");
            console.log("更新失败")
          }
        })
      }
      
    },
    clickTab(_index){
      //console.log(_index)
      //console.log(this.tabs.length)
      let templist=this.allIndexList[_index];
      this.allIndexList.splice(_index,this.tabs.length-_index);
      this.tabs.splice(_index,this.tabs.length-_index);
      this.tabs.push(this.defaultObj);
      this.setListArr(templist)
      //console.log(this.allIndexList[_index])
      //arr.splice(1,1)
    },
    locationSet(lontatStr,_icon,_obj){
      let _this=this;
      if(lontatStr){
        let lon=lontatStr.split("_")[0];
        let lat=lontatStr.split("_")[1];
        _this.address=lontatStr.split("_")[2];
        _this.locationSetStr=lontatStr;
        //
        let infoWindow = new AMap.InfoWindow({
          offset: new AMap.Pixel(0, -10),
          closeWhenClickMap: true
        });
        let lonlat=new AMap.LngLat(parseFloat(lon), parseFloat(lat))
        let startIcon;
        let marker;
        //判断是否传入自定义图标
        if(_icon){
          _this.typeShow="1";
          // 创建一个 Icon
          startIcon = new AMap.Icon({
              // 图标尺寸
              size: new AMap.Size(25, 34),
              // 图标的取图地址
              image: _icon,
              // 图标所用图片大小
              imageSize: new AMap.Size(25, 34),
              // 图标取图偏移量
              //imageOffset: new AMap.Pixel(-9, -3)
          });
          // 创建一个 Marker 实例：
          marker = new AMap.Marker({
              position:lonlat ,   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
              title:_this.address,
              icon: startIcon,
              size: new AMap.Size(20, 30),
              attr:_obj,
          });
          marker.on("click", function(e) {
              console.log("click==>")
              infoWindow.close();
              console.log(e);
              console.log(e.target.w.attr)
              let content=`<div class="infoWindow_div" style=' width: 60vw;height: 30vw;overflow-y: auto;'><ul style="padding-top: 5px;height: 100%;overflow-y: auto;">`;
              let obj=e.target.w.attr;
              if(typeof(obj.eventtitle)=="undefined"){
                console.log("不是event")
                content+=`<li><span>名称：</span><span>`+obj.orgname+`</span></li>`
                content+=`<li><span>地址：</span><span>`+obj.address+`</span></li>`
              }else{
                console.log("是event")
                content+=`<li><span>名字：</span><span>`+obj.eventtitle+`</span></li>`
                content+=`<li><span>地址：</span><span>`+obj.eventaddress+`</span></li>`
              }
              content+=`</ul></div>`
              infoWindow.setContent(content);
              let postionObj = [];
              /* var zoom=map.getZoom();
              let clat=0.000001*(zoom+zoom*4);
              console.log(e.target.getPosition()) */
              postionObj = [(e.target.getPosition().lng), e.target.getPosition().lat];
              infoWindow.open(_this.maps, postionObj);
          })
          // 将创建的点标记添加到已有的地图实例：
          _this.maps.add(marker);
        }else{
          if(_this.marker){
            // 移除已创建的 marker
            _this.maps.remove(_this.marker);
          }
          // 创建一个 Marker 实例：
          _this.marker = new AMap.Marker({
              position:lonlat ,   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
              title:_this.address,
              icon: startIcon,
              size: new AMap.Size(20, 30),
          });
          _this.maps.add(_this.marker);
          _this.maps.setCenter(lonlat);
          _this.maps.setZoom(15);
        }
      }
      
      
     

    }
    ,navigationLine(startLngLatStr,endLngLatStr,_obj){
      console.log("invoking navigationLine ...")
      let _this=this;
      AMap.plugin('AMap.Driving', function() {
        var driving = new AMap.Driving({
          // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
          policy:AMap.DrivingPolicy.LEAST_TIME,
          showTraffic:false,
          map:_this.maps,//线路等均会自动添加到此地图上
          hideMarkers:true,//设置隐藏路径规划的起始点图标
        })
        var startLngLat = [parseFloat(startLngLatStr.split("_")[0]),parseFloat(startLngLatStr.split("_")[1])]
        var endLngLat = [parseFloat(endLngLatStr.split("_")[0]),parseFloat(endLngLatStr.split("_")[1])]
        
        driving.search(startLngLat, endLngLat, function (status, result) {
          console.log("调用成功")
          // 未出错时，result即是对应的路线规划方案
          //console.log(status,result);
         
          let lineArr=[];
          if(result.routes&&result.routes.length>0){
            if(_obj){
              console.log("通知赋值",_obj)
              let distance=result.routes[0].distance;
              let time=result.routes[0].time;
              _this.upNotification(time,distance,_this.eventObj.dispatchcasetime);
              
              _this.updateArriveState("1");//更新
            }
            //自己划线逻辑
            // if(result.routes[0].steps&&result.routes[0].steps.length>0){
            //   //console.log(result.routes[0].steps)
            //   result.routes[0].steps.forEach((item,index) => {
            //     //console.log(item);
            //     let lonlat=[item.start_location.lng,item.start_location.lat]
            //     //console.log(lonlat)
            //     lineArr.push(lonlat)
            //   });
            //   _this.drawLine(lineArr);
            // }

            
          }
          
          
        })
      })

    },
    drawLine(_lineArr){
      //this.getLineCenter(_lineArr)
      // 绘制轨迹
      var polyline = new AMap.Polyline({
          map: this.maps,
          path: _lineArr,
          showDir:true,
          strokeColor: "#28F",  //线颜色
          // strokeOpacity: 1,     //线透明度
          strokeWeight: 6,      //线宽
          // strokeStyle: "solid"  //线样式
      });
      this.maps.setZoom(1);
    },
    getLineCenter(lineArr){
				let _this=this;
				let newlineArr=[];
				lineArr.forEach(function(item,index){
					newlineArr.push(item)
				})
        //console.log(newlineArr);
        //debugger
				newlineArr.sort(function(a,b){return a[0] - b[0];});
				console.log("最大lng==>"+newlineArr[newlineArr.length - 1][0]+"==最小lng==>"+newlineArr[0][0])
				let lng=(newlineArr[newlineArr.length - 1][0]+newlineArr[0][0])/2;
				newlineArr.sort(function(a,b){return a[1] - b[1];});
				console.log("最大lat==>"+newlineArr[newlineArr.length - 1][1]+"==最小lat==>"+newlineArr[0][1])
				let lat=(newlineArr[newlineArr.length - 1][1]+newlineArr[0][1])/2;
        let lonlat=new AMap.LngLat(lng, lat)
        //debugger
        _this.maps.setCenter(lonlat);
        _this.maps.setZoom(4);
				//vm.bases.maxMonitorTimeStr=timeArr[timeArr.length - 1];
			}
  },mounted:function () {
    let _this=this;
    _this.maps="";
    console.log("come in commonMap")
    _this.maps = new AMap.Map(_this.initName, {
      zoom:11,//级别
      center: [116.397428, 39.90923],//中心点坐标
      resizeEnable: true,
    });
    if(_this.Enable){
       _this.maps.on("click", function(e) {
        //console.log("点击地图功能")
        //console.log(e)
        AMap.service('AMap.Geocoder',function(){//回调函数
            //实例化Geocoder
            let geocoder = new AMap.Geocoder({
                city: ""//城市，默认：“全国”
            });
            var lnglatXY=[e.lnglat.getLng(), e.lnglat.getLat()];//地图上所标点的坐标
            geocoder.getAddress(lnglatXY, function(status, result) {
              console.log(status,result)
                let formattedAddress;
                if (status === 'complete' && result.info === 'OK') {
                    //获得了有效的地址信息:
                    formattedAddress= result.regeocode.formattedAddress;
                }else{
                    formattedAddress="获取失败";
                    //获取地址失败
                }
                let resultStr=e.lnglat.getLng()+"_"+e.lnglat.getLat()+"_"+formattedAddress;
                _this.locationSet(resultStr);
                console.log(formattedAddress);
              
            });
        })
      })
    }
   
  }
};
</script>
<style lang="less" scoped>
.map_big{
    width: 100%;
    background: #fff;
    position: relative;
    .infoWindow_div{
      width: 30vw;
      height: 20vw;
      background: #39b5f9;
    }
    .allpx{
      display: block;
      width: 26px;
      height: 26px;
      position: absolute;
      right: 4vw;
      top: 12vw;
      z-index: 100;
      background: #409eff;
      border-radius: 4px;
      padding-left: 5.2px;
      color: #fff;
      line-height: 26px;
      img{
        width: 15px;
        vertical-align: middle;
        margin-bottom: 2px;
      }
    }
    .map_notification{
      width: 100%;
      height: 30px;
      display: block;
      position: absolute;
      line-height: 30px;
      bottom: 1px;
      background-color: rgba(0,0,0,.35);
      color: #fff;
      padding-left: 4%;
      -webkit-box-shadow: 0 0 4px 0 rgba(0,0,0,.44);
      bottom: -9vw;
      /* box-shadow: 0 0 4px 0 rgba(0,0,0,.44); */
      z-index: 10;
      img{
        width: 16px;
        vertical-align: middle;
        margin-top: 7px;
        float: left;
      }
      .handle_text{
        width: 75%;
        height: 30px;
        line-height: 30px;
        display: block;
        float: left;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        span{
          height: 100%;
          display: inline-block;
          float: left;
        }
      }
      .handle_btn_div{
        width: 25%;
        height: 35px;
        display: inline-block;
        padding-top: 2px;
        span{
          display: block;
          width: 80%;
          height: 24px;
          line-height: 24px;
          border-radius: 4px;
          text-align: center;
          background: #fe9d33;
          
        }
      }
    }
    .container{
      width: 100%;
      height: 100%;
    }
    .map_title{
      width: 100%;
      height: 40px;
      background: #f4f7f8;
      line-height: 40px;
      padding-left: 5%;
      img{
        width: 75%;
        vertical-align: middle;
      }
      .location_content{
        display: inline-block;
        width: 67%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        padding-top: 1px;
      }
      .location_after{
        color: #39b5f9;
        width: 25%;
        img{
          width: 18%;
          margin-bottom: 3px;
        }
      }
      span{
        display: inline-block;
        float: left;
      }
      span:nth-child(1){
        width: 7%;
      }
    }
}

</style>
